package com.goldgov.jdbc.service.impl;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.goldgov.jdbc.dao.JdbcConfigDao;
import com.goldgov.jdbc.service.JdbcConfig;
import com.goldgov.jdbc.service.JdbcConfigService;

@Service
public class JdbcConfigServiceImpl implements JdbcConfigService{

	@Autowired
	private JdbcConfigDao configDao;

	@Override
	public void saveConfig(JdbcConfig config) {
		if(config.getConfigID() != null && !"".equals(config.getConfigID())) {
			configDao.updateConfig(config);
		}else {
			configDao.addConfig(config);
		}
	}

	@Override
	public void deleteConfig(String configID) {
		configDao.deleteConfig(configID);
	}
	
	@Override
	public JdbcConfig getConfig(String configID) {
		return configDao.getConfig(configID);
	}

	@Override
	public List<JdbcConfig> listConfig(String projectID) {
		return configDao.listConfig(projectID);
	}

	@Override
	public boolean testConfig(JdbcConfig config) {
		try (Connection connection = DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword())){
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	@Override
	public List<String> listTableNames(String configID) {
		JdbcConfig config = getConfig(configID);
		List<String> tableNameList = new ArrayList<>();
		
		try (Connection connection = DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword())){
			DatabaseMetaData metaData = connection.getMetaData();
			ResultSet tables = metaData.getTables(null,null,null,new String[]{"TABLE"});
			while(tables.next()){
				String tableName = tables.getString("TABLE_NAME");
				tableNameList.add(tableName);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return tableNameList;
	}
	

}
